import { _delete, get, post } from '@/utils/requestUtil'
import { Spin, Modal, message, Empty } from 'antd'
import React, { Component } from 'react'
import { PlusOutlined, EditOutlined } from '@ant-design/icons'
import InputWidget from '@/components/basicWidget/InputWidget'
import Button, { TableButton } from '@/components/basicWidget/Button'
import { commonQueryByCode, deleteDocumentsByCondition } from '@/service/document/documentService'
import DocumentList from '@/components/basicWidget/DocumentList'
import { Link } from 'react-router-dom'

import './index.css'

const { confirm } = Modal

/**
 * 个人中心-个人博客分类管理
 */
class PersonalBlogClassification extends Component {

    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            blogLabel: [],
            blogList: [],
            checkedLabelId: null,
            user: null,
            addModalVisual: false,
            addModalKey: new Date().getTime() + '',
            classInfo: { id: null }, // modal框分类内容
            blogListLoading: false //博客列表获取时候的状态
        }
    }

    async componentDidMount() {
        const { user } = this.props
        if (!user) return
        let blogLabel = []
        let checkedLabelId = null

        //查询客户自定义分类
        const response = await get(`/blog/get/blogClass/${user.id}`)
        if (response && response.data) blogLabel = response.data
        if (blogLabel.length > 0) checkedLabelId = blogLabel[0].id //默认选中第一个

        //查询类别下博客列表
        const blogList = await getBlogListInBlogClass(checkedLabelId)

        await new Promise(resolve => {
            this.setState({
                user,
                blogLabel,
                checkedLabelId,
                blogList
            }, resolve)
        })
        await new Promise(resolve => { this.setState({ loading: false }, resolve) })
    }

    /**
     * 删除博客分类
     */
    deleteBlogClass = async () => {
        const { id, className } = this.state.classInfo
        if (!id) return
        confirm({
            content: `确定要删除[${className}]标签吗`,
            onOk: async () => {
                const response = await _delete(`/blog/delete/blogClass/${id}`)
                if (response && response.data === true) {
                    message.success('删除成功')
                    const newBlogLabel = this.state.blogLabel.filter(item => {
                        return item.id !== id
                    })
                    let newCheckedLabelId = this.state.checkedLabelId
                    let newBlogList = this.state.blogList
                    //如果删除的是当前选中的标签
                    if (id === this.state.checkedLabelId) {
                        newCheckedLabelId = newBlogLabel.length > 0 ? newBlogLabel[0].id : null
                        //查询类别下博客列表
                        newBlogList = newCheckedLabelId ? await getBlogListInBlogClass(newCheckedLabelId) : []
                    }
                    await new Promise(resolve => {
                        this.setState({
                            addModalVisual: false,
                            blogLabel: newBlogLabel,
                            checkedLabelId: newCheckedLabelId,
                            blogList: newBlogList
                        }, resolve)
                    })
                }
            },
            onCancle: async () => {
                return
            }
        })
    }

    renderAddModal = () => {
        return (
            <Modal
                title='新增分类'
                open={this.state.addModalVisual}
                onCancel={async () => {
                    await new Promise(resolve => {
                        this.setState({
                            addModalVisual: false
                        }, resolve)
                    })
                }}
                footer={null}
            >
                <div
                    key={this.state.addModalKey}
                    className='PersonalBlogClassification-addModal'
                >
                    <InputWidget
                        prefixName={{ content: '分类名称' }}
                        hiddenClearButton={true}
                        value={this.state.classInfo.className}
                        onChange={async (value) => {
                            await new Promise(resolve => {
                                this.setState({
                                    classInfo: {
                                        ...this.state.classInfo,
                                        className: value
                                    }
                                }, resolve)
                            })
                        }}
                    >
                    </InputWidget>
                    <div>
                        <Button
                            style={{ marginRight: '10px' }}
                            onClick={this.saveHandler}
                        >保存</Button>
                        {
                            this.state.classInfo.id ?
                                <Button
                                    style={{ backgroundColor: 'var(--bg-three-color)' }}
                                    onClick={this.deleteBlogClass}
                                >
                                    删除
                                </Button> : ''
                        }
                    </div>
                </div>
            </Modal>
        )
    }

    saveHandler = async () => {
        const response = await post('/blog/save/blogClass', {
            body: JSON.stringify(this.state.classInfo)
        })
        if (response && response.code === 200) {
            if (response.data === false) {
                message.warning(response.message)
                return false
            }
            const blogLabelInfo = await get(`/blog/get/blogClass/${this.props.user.id}`)
            await new Promise(resolve => {
                this.setState({
                    addModalVisual: false,
                    blogLabel: blogLabelInfo ? blogLabelInfo.data : [],
                    classInfo: response.data
                }, resolve)
            })
            message.success('保存成功')
        }
    }

    /**
     * 从标签移除博客
     * @param {*} blogId 博客id
     */
    removeBlogFromClass = async (blogId) => {
        confirm({
            content: `确定要从标签移除此博客吗`,
            onOk: async () => {
                const blogClassId = this.state.checkedLabelId
                const response = await deleteDocumentsByCondition({
                    serviceName: 'blog',
                    collectionName: 'customer_blogclass_blog_info',
                    searchFactory: [
                        {
                            fieldName: 'blogId',
                            fieldValue: blogId,
                            operate: 'eq'
                        }, 
                        {
                            fieldName: 'blogClassId',
                            fieldValue: blogClassId,
                            operate: 'eq'
                        }
                    ]
                })
                if (response && response.data === true) {
                    message.success('操作成功')
                    const newBlogList = await getBlogListInBlogClass(blogClassId)
                    await new Promise(resolve => {
                        this.setState({
                            blogList: newBlogList
                        }, resolve)
                    })
                }
            },
            onCancle: async () => {
                return
            }
        })
    }

    actionColumns = (columns, data) => {
        columns.push({ title: '操作', dataIndex: 'operate1' })
        data = data.map(item => {
            item.operate1 = (
                <Link to={`/write/blog/${item.id}`} key={item.id + '_1'}>编辑</Link>
            )
            return item
        })
        columns.push({ title: '操作', dataIndex: 'operate2' })
        data = data.map(item => {
            item.operate2 = (
                <TableButton onClick={async () => {await this.removeBlogFromClass(item.id)}} key={item.id + '_2'}>移除博客</TableButton>
            )
            return item
        })
        return { newColumns: columns, newData: data }
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <>
                <div className='PersonalBlogClassification-main'>
                    <div className='PersonalBlogClassification-label'>
                        {
                            this.state.blogLabel.map(item => {
                                if (item.id === this.state.checkedLabelId) {
                                    return (
                                        <div className='PersonalBlogClassification-label-checked' key={item.id}>
                                            <span style={{ marginRight: '10px' }}>{item.className}</span>
                                            <span
                                                onClick={async () => {
                                                    await new Promise(resolve => {
                                                        this.setState({
                                                            addModalKey: new Date().getTime() + '',
                                                            addModalVisual: true,
                                                            classInfo: { ...item }
                                                        }, resolve)
                                                    })
                                                }}
                                            ><EditOutlined /></span>
                                        </div>
                                    )
                                } else {
                                    return (
                                        <div
                                            className='PersonalBlogClassification-label-item'
                                            key={item.id}
                                        >
                                            <span
                                                onClick={async () => {
                                                    await new Promise(resolve => {
                                                        this.setState({
                                                            checkedLabelId: item.id,
                                                            blogListLoading: true
                                                        }, resolve)
                                                    })
                                                    const blogList = await getBlogListInBlogClass(item.id)
                                                    await new Promise(resolve => {
                                                        this.setState({
                                                            blogList,
                                                            blogListLoading: false
                                                        }, resolve)
                                                    })
                                                }}
                                                style={{ marginRight: '10px' }}
                                            >{item.className}</span>
                                            <span
                                                onClick={async () => {
                                                    await new Promise(resolve => {
                                                        this.setState({
                                                            addModalKey: new Date().getTime() + '',
                                                            addModalVisual: true,
                                                            classInfo: { ...item }
                                                        }, resolve)
                                                    })
                                                }}
                                            ><EditOutlined /></span>
                                        </div>
                                    )
                                }
                            })
                        }
                        <span
                            className='PersonalBlogClassification-label-add'
                            onClick={async () => {
                                await new Promise(resolve => {
                                    this.setState({
                                        addModalVisual: true,
                                        addModalKey: new Date().getTime() + '',
                                        classInfo: { id: null }
                                    }, resolve)
                                })
                            }}
                        >
                            <PlusOutlined /> 新增
                        </span>
                    </div>
                    <div className='PersonalBlogClassification-blog-list'>
                        {
                            this.state.blogListLoading === true ?
                                <Spin /> :
                                this.state.blogList.length > 0 ?
                                    <DocumentList
                                        columns={[
                                            { title: '标题', dataIndex: 'blogTitle' },
                                            { title: '创建时间', dataIndex: 'createTime' },
                                            { title: '最后修改时间', dataIndex: 'alterTime' },
                                            { title: '状态', dataIndex: 'state' },
                                            { title: '浏览量', dataIndex: 'views' },
                                            { title: '点赞量', dataIndex: 'agree' }
                                        ]}
                                        data={this.state.blogList}
                                        hideSelect={true}
                                        bordered={true}
                                        pageSizeOptions={[10, 20, 50, 100]}
                                        showTotal={true}
                                        actionColumns={this.actionColumns}
                                        rowKey={(record) => {return record.id}}
                                    >
                                    </DocumentList>
                                    : <Empty
                                        description={false}
                                        imageStyle={{ height: '200px', marginTop: '100px' }}
                                    />
                        }
                    </div>
                </div>
                {this.renderAddModal()}
            </>
        )
    }
}

export default PersonalBlogClassification

/**
 * 根据个人博客分类id查询下属博客信息
 * @param {*} classId 博客分类id
 * @return blogList
 */
export async function getBlogListInBlogClass(classId) {
    let blogList = []
    if (classId != null) {
        const response = await commonQueryByCode({
            commandCode: 'getBlogListInBlogClass',
            searchFactory: [
                {
                    fieldName: 'classId',
                    fieldValue: classId,
                    operate: 'eq',
                }
            ]
        })
        if (response && response.code === 200) {
            blogList = response.data.documents.map(item => {
                return item.content
            })
        }
    }
    return blogList
}
